<template>
	<view class="tabContent" :style="{ marginTop:$u.addUnit(44 + $u.sys().statusBarHeight,'px') }">
		<u-navbar title="模块" :autoBack="false" leftIcon="" :safeAreaInsetTop="true"></u-navbar>

		<u-swiper :list="list1" height="260rpx" :interval="6000" circular imgMode="scaleToFill"></u-swiper>

		<view class="commonBox">
			<u-tabs lineColor="#51d0d0" :activeStyle="{color:'#51d0d0',fontWeight:'500',transform:'scale(1.05)'}"
				:list="moduleTypes" :current="currModuleType" @change="switchModuleType">
			</u-tabs>

			<view class="module" v-for="(module,index) in currModules" :key="index">
				<view class="module-left">
					<u-icon name="grid" color="#51d0d0" size="60rpx"></u-icon>
				</view>
				<view class="module-middle">
					<view class="module-middle-title">
						<text>{{module.ModuleName}}</text>
					</view>
					<view class="module-middle-subtitle">
						<text>{{module.Description}}</text>
					</view>
				</view>
				<view class="module-right">
					<u-button v-if="currModuleType==0" color="#1989fa" size="small" :plain="true" :hairline="true"
						text="立即使用" @click="initModule(module)"></u-button>
					<u-button v-else color="#1989fa" size="small" :plain="true" :hairline="true" text="申请开通"
						@click="applyModule(module)"></u-button>
				</view>
			</view>

			<view class="module" v-if="currModuleType==0">
				<view class="module-left">
					<u-icon name="grid" color="#51d0d0" size="60rpx"></u-icon>
				</view>
				<view class="module-middle">
					<view class="module-middle-title">
						<text>古越Mes</text>
					</view>
				</view>
				<view class="module-right">
					<u-button color="#1989fa" size="small" :plain="true" :hairline="true" text="立即使用"
						@click="ToMesIndex"></u-button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				modules: [],
				currModules: [], // 当前模块列表
				openModules: [], // 已开通模块列表
				closeModules: [], // 未开通模块列表
				moduleTypes: [], // 模块分类
				currModuleType: 0, // 当前模块分类
				list1: [
					'../../static/image/Img/pp.png',
					'../../static/image/Img/p1.png',
					'../../static/image/Img/p2.png',
				]
			}
		},
		created() {
			let that = this;
			that.initModuleTypes();
		},
		mounted() {
			let that = this;
			uni.$on('refreshCenter', function(ret) {
				that.initModuleTypes();
			});
		},
		methods: {
			// 初始化模块分类
			initModuleTypes() {
				let that = this;
				that.modules = that.$store.state.APPModules;
				// console.log(that.modules);
				that.openModules = that.modules.filter(module => module.Available == 1);
				that.closeModules = that.modules.filter(module => module.Available == 0);
				let openNums = that.openModules.length;
				let closeNums = that.closeModules.length;
				that.moduleTypes = [{
					name: '已开通',
					badge: {
						value: openNums
					}
				}, {
					name: '未开通',
					badge: {
						value: closeNums
					}
				}];
				that.currModules = that.openModules;
			},

			// 切换模块分类
			switchModuleType(item) {
				let that = this;
				that.currModuleType = item.index;
				if (item.index == 0) {
					that.currModules = that.openModules;
				} else {
					that.currModules = that.closeModules;
				}
			},

			// 申请开通模块
			applyModule(module) {
				console.log(module);
			},

			ToMesIndex() {

				let MesBasicInfo = {
					UserName: this.$store.state.UserInfo.UserName,
					openDate: new Date(),
					warehouse: '测试仓库',
				}

				this.$store.commit('GuyueModule/ChangeAndSetStateData', {
					Name1: 'MesBasicInfo',
					data: MesBasicInfo
				})

				uni.navigateTo({
					url: '/mes/index/index'
				})
			},

			// 初始化模块页面
			initModule(module) {
				let that = this;
				this.Request.request('getAPPModulePages', {
					UserID: this.$store.state.UserInfo.UserID,
					APPType: module.ModuleID,
				}, (ret) => {
					// console.log(ret)
					if (ret.status == 200) {
						const data = ret.data.ds;
						const ds1 = ret.data.ds1;

						// 预先处理ds1，以APPFunID为键，值为对应的数组  
						const ds1Map = new Map(ds1.map(row => [row.APPFunID, [row]]).reduce((acc, [key, val]) => {
							acc.set(key, [...acc.get(key) || [], ...val]);
							return acc;
						}, new Map()));

						let organizedData = that.organizeByTreeTypeName(data, ds1Map);
						organizedData = organizedData.sort((a, b) => a.TreeType - b.TreeType);

						// 这里获取了模块以及页面的权限树，将 IsTabbar 为true的筛选出来，作为底部栏数据

						let TabbarData = organizedData.flatMap(item => item.Node.filter(row => row.IsTabbar)).sort(
							(a, b) => a.APFunCode - b.APFunCode); // 对结果进行排序
						// console.log(TabbarData)

						let workspaceData = organizedData.flatMap(item => item.Node.filter(row => !row.IsTabbar))
							.sort(
								(a, b) => a.APFunCode - b.APFunCode); // 对结果进行排序

						// console.log(workspaceData)

						uni.removeStorageSync('ModuleInfo_All');
						uni.removeStorageSync('Module_Tabbar');

						that.$store.commit('ChangeAndSetStateData', {
							Name1: 'ModuleInfo_All',
							data: [],
						});

						// 模块数据持久化 
						that.$store.commit('ChangeAndSetStateData', {
							Name1: 'Module_Tabbar',
							data: [],
						})

						// 模块数据持久化（没什么意义，登录一定会获取一遍）
						that.$store.commit('ChangeAndSetStateData', {
							Name1: 'ModuleInfo_All',
							data: organizedData,
							StorageName: 'ModuleInfo_All',
							StorageData: JSON.stringify(organizedData),
						});

						// 模块数据持久化 
						that.$store.commit('ChangeAndSetStateData', {
							Name1: 'Module_Tabbar',
							data: TabbarData,
							StorageName: 'Module_Tabbar',
							StorageData: JSON.stringify(TabbarData),
						})


						let url = '';
						// 小工单/QMS直接跳转
						if (module.ModuleID == 2 || module.ModuleID == 3) {
							let homePage = module.authPages.find(item => item.IsHomepage);
							if (homePage && homePage != undefined) {
								url = homePage.AP_Link; // 设置首页路径
								uni.navigateTo({
									url: url
								})
							} else {
								uni.showToast({
									icon: 'none',
									title: '当前应用未设置首页!'
								})
							}
						} else {
							url = '/commonPage/Module/index?moduleID=' + module.ModuleID + '&index=0';
							uni.navigateTo({
								url: url
							})
						}
						that.$store.commit('ChangeAndSetStateData', {
							Name1: 'ActiveModule',
							data: module,
							StorageName: 'ActiveModule',
							StorageData: JSON.stringify(module),
						})
						// console.log(url);
					}
				}, (err) => {
					// 处理错误  
				});
			},

			organizeByTreeTypeName(arr, ds1Map) {
				// 创建一个映射来按TreeType分组数据  
				const groupedData = {};

				arr.forEach((item) => {
					const treeType = item.TreeType;
					const treeTypeName = item.TreeTypeName; // 用于分组的键  

					if (!(treeTypeName in groupedData)) {
						groupedData[treeTypeName] = {
							TreeType: treeType, // 保留TreeType  
							APPType: item.appType, // 保留APPType
							Node: [],
						};
					}

					// 检查ds1Map中是否有匹配的APPFunID  
					if (ds1Map.has(item.APPFunID)) {
						groupedData[treeTypeName].Node.push({
							...item,
							IconApprove: ds1Map.get(item.APPFunID), // 如果需要，直接添加IconApprove  
						});
					} else {
						groupedData[treeTypeName].Node.push({
							...item,
							IconApprove: []
						});
					}
				});

				// 提取分组后的数据为数组，并可能按某种逻辑排序（这里不排序，因为TreeTypeName已经是分组键）  
				const sortedData = Object.entries(groupedData).map(([treeTypeName, group]) => ({
					TreeTypeName: treeTypeName,
					...group, // 展开分组对象，它包含TreeType, APPType, APPFunID, 和 Node 数组  
				}));

				return sortedData;
			}
		}
	}
</script>

<style lang="scss" scoped>
	$h-padding: 15rpx;
	$v-padding: 20rpx;
	$radius: 10rpx;

	.tabContent {
		display: flex;
		flex-direction: column;
		background-color: #f8f8f8;
		padding: $v-padding $h-padding;

		.commonBox {
			display: flex;
			flex-direction: column;
			padding: $v-padding 0 0;
			margin-bottom: $v-padding;

			.u-tabs {
				padding-bottom: 10rpx;
			}

			.module {
				display: flex;
				justify-content: center;
				align-items: center;
				// height: 80px;
				background-color: #fff;
				padding: 20rpx;
				border-radius: 5px;
				margin-bottom: 10px;

				&-left {
					display: flex;
					justify-content: center;
					align-items: center;
					width: 80rpx;
				}

				&-middle {
					display: flex;
					flex-direction: column;
					align-items: flex-start;
					justify-content: flex-start;
					// max-height: 80px;
					overflow: hidden;
					flex: 1;

					&-title {
						display: flex;
						align-items: center;
						font-size: 28rpx;
						font-weight: 500;
						min-height: 25px;
						line-height: 16px;
						padding: 0 5px;
						color: #044569;
					}

					&-subtitle {
						margin-top: 10rpx;
						padding: 0 5px;
						font-size: 24rpx;
						// height: 55px;
						min-height: 100rpx;
						color: #999;
					}
				}

				&-right {
					display: flex;
					justify-content: center;
					align-items: center;
					width: 80px;
				}
			}

		}
	}
</style>